﻿<%@ WebHandler Language="C#" Class="PublicInfo" %>

using System;
using System.Web;
using Chenxin.Lib.Utility;
using System.Data;
using System.Text;
using System.Data.SqlClient;

public class PublicInfo : AjaxHandlerBase
{

   override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";

        if (!string.IsNullOrEmpty(context.Request.Params["op"]))
        {
            //处理类型
            string strOperate = context.Request.Params["op"];

            switch (strOperate.Trim())
            {
                case "search":
                    Search(context);
                    break;
                default:
                    break;
            }
        }
    }

    public void Search(HttpContext context)
    {
        //查询条件
        Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
        Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
        Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
        Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
        Guid employee = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);

        //判断权限范围/////////////////////////////////////////////
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        if (employee != Guid.Empty)
            sb.AppendFormat(" AND (p.PublisherId = '{0}') ", employee);
        else if (departs != Guid.Empty)
            sb.AppendFormat(" AND (p.DepartId = '{0}')", departs);
        else if (businessdistrict != Guid.Empty)
        {
            Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
            string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
            if (!cs.Hit)
            {
                item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
            }

            if (item == null)
            {
                context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失"));
                return;
            }
            sb.AppendFormat(" AND (p.DepartId in (Select DepartId from Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
        }
        else if (company != Guid.Empty)
            sb.AppendFormat(" AND p.CompanyId = '{0}'", company);
        else if (city != Guid.Empty)
            sb.AppendFormat(" AND p.CityId = '{0}'", city);
        else
            sb.AppendFormat(" AND p.CompanyId = '{0}'", CurrentUserInfo.CompanyId);

        System.Text.StringBuilder sb1 = new System.Text.StringBuilder();

        string InfoType = context.Request.Params["Type"];
        if (string.IsNullOrEmpty(InfoType))
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, "参数不匹配", ""));
            return;
        }
        sb1.AppendFormat(" p.InfoType = '{0}'", InfoType);
        sb1.Append(" AND DATEDIFF(DD,GETDATE(),p.PublishTime) <= 0 and p.IsDel = 'false' ");

        //我的信息
        if (!string.IsNullOrEmpty(context.Request.Params["user"]) && "myself".Equals(context.Request.Params["user"]))
        {
            sb1.AppendFormat("AND p.PublisherId = '{0}'", CurrentUserInfo.UserId);
        }
        else
        {
            sb1.Append(addPermitCondition(InfoType));
               
            if (!String.IsNullOrEmpty(sb.ToString()))
                sb1.Append(sb.ToString());
        }

        string strSubject = context.Request.Params["Subject"];//信息主题
        string strPublishtime = context.Request.Params["publishtime"];//发件时间
        string strIspopup = context.Request.Params["ispopup"];//弹出
        
        if (!string.IsNullOrEmpty(strSubject))
        {
            sb1.AppendFormat("AND p.Subject like '%{0}%'", strSubject);
        }
        if (!string.IsNullOrEmpty(strPublishtime))
        {
            switch (strPublishtime)
            {
                case "10"://今日
                    sb1.AppendFormat("AND DATEDIFF(DD,GETDATE(),p.PublishTime) = 0");
                    break;
                case "20"://前日
                    sb1.AppendFormat("AND DATEDIFF(DD,GETDATE(),p.PublishTime) = -1");
                    break;
                case "30"://本周
                    sb1.AppendFormat("AND DATEDIFF(WK,GETDATE(),p.PublishTime) = 0");
                    break;
                case "40"://本月
                    sb1.AppendFormat("AND DATEDIFF(MM,GETDATE(),p.PublishTime) = 0");
                    break;
                case "50"://本年
                    sb1.AppendFormat("AND DATEDIFF(YY,GETDATE(),p.PublishTime) = 0");
                    break;
                case "60"://去年
                    sb1.AppendFormat("AND DATEDIFF(YY,GETDATE(),p.PublishTime) = -1");
                    break;
                default:
                    break;
            }
        }
        if (!string.IsNullOrEmpty(strIspopup))
        {
            switch (strIspopup)
            { 
                case "10"://弹出
                    sb1.AppendFormat("AND p.isPopUp = 'true'", strSubject);
                    break;
                case "20"://不弹出
                    sb1.AppendFormat("AND p.isPopUp = 'false'", strSubject);
                    break;
                default:
                    break;  
            }
            
        }
        
        SearchPublicInfo(context, sb1.ToString());
        
    }

    //权限判断
    public string addPermitCondition(string InfoType)
    {
        StringBuilder strRet = new StringBuilder();
        //权限项
        string PermitAll = "";
        string PermitCity = "";
        string PermitCompany = "";

        switch (InfoType)
        {
            case "0":
                PermitAll = Constants.Permit_ViewAllBulletin;
                PermitCity = Constants.Permit_ViewCityBulletin;
                PermitCompany = Constants.Permit_ViewCompanyBulletin;
                break;
            case "10":
                PermitAll = Constants.Permit_ViewAllNotice;
                PermitCity = Constants.Permit_ViewCityNotice;
                PermitCompany = Constants.Permit_ViewCompanyNotice;
                break;
            case "20":
                PermitAll = Constants.Permit_ViewAllFirstHanded;
                PermitCity = Constants.Permit_ViewCityFirstHanded;
                PermitCompany = Constants.Permit_ViewCompanyFirstHanded;
                break;
            case "30":
                PermitAll = Constants.Permit_ViewAllSecondHanded;
                PermitCity = Constants.Permit_ViewCitySecondHanded;
                PermitCompany = Constants.Permit_ViewCompanySecondHanded;
                break;
            case "40":
                PermitAll = Constants.Permit_ViewAllOthersInfo;
                PermitCity = Constants.Permit_ViewCityOthersInfo;
                PermitCompany = Constants.Permit_ViewCompanyOthersInfo;
                break;
            case "50":
                PermitAll = Constants.Permit_ViewAllParticular;
                PermitCity = Constants.Permit_ViewCityParticular;
                PermitCompany = Constants.Permit_ViewCompanyParticular;
                break;
            case "100":
                PermitAll = Constants.Permit_ViewAllItDept;
                PermitCity = Constants.Permit_ViewCityItDept;
                PermitCompany = Constants.Permit_ViewCompanyItDept;
                break;
            case "110":
                PermitAll = Constants.Permit_ViewAllCoPower;
                PermitCity = Constants.Permit_ViewCityCoPower;
                PermitCompany = Constants.Permit_ViewCompanyCoPower;
                break;
            case "120":
                PermitAll = Constants.Permit_ViewAllLegal;
                PermitCity = Constants.Permit_ViewCityLegal;
                PermitCompany = Constants.Permit_ViewCompanyLegal;
                break;
            case "130":
                PermitAll = Constants.Permit_ViewAllPersonnel;
                PermitCity = Constants.Permit_ViewCityPersonnel;
                PermitCompany = Constants.Permit_ViewCompanyPersonnel;
                break;
            case "140":
                PermitAll = Constants.Permit_ViewAllCaseHall;
                PermitCity = Constants.Permit_ViewCityCaseHall;
                PermitCompany = Constants.Permit_ViewCompanyCaseHall;
                break;
        }

        //查看所有公告信息权限
        if (CurrentUserInfo.ContainsPermit(PermitAll))
        {

        }
        //查看城市公告信息权限
        else if (CurrentUserInfo.ContainsPermit(PermitCity))
        {
            strRet.AppendFormat("AND p.CityId = '{0}' ", CurrentUserInfo.CityId);
        }
        //查看公司公告信息权限
        else if (CurrentUserInfo.ContainsPermit(PermitCompany))
        {
            strRet.AppendFormat("AND p.CompanyId = '{0}' ", CurrentUserInfo.CompanyId);
        }
        else
        {
            strRet.AppendFormat("AND p.PublisherId = '{0}'", CurrentUserInfo.UserId);
        }
        return strRet.ToString();
    }

    public void SearchPublicInfo(HttpContext context, string strWhere)
    {
        try
        {
            
            //所要查询的表名
            string strTableName = "Pblish_Info as p left outer join Attachment as a on p.RecordId = a.RelationId ";
            //排序
            string strOrderField = "p.PublishTime desc";

            int count = 0;
            Constants.Pagination stuPg = new Constants.Pagination();

            //页码
            int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            //页显示行数
            int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            //欲选择字段列表 
            string FieldList = "p.*,a.[Path],a.[Type],a.FileName";
            //子查询欲选择字段列表
            string TableFieldList = "p.*,a.[Path],a.[Type],a.FileName";

            //根据sql执行查询
            DataSet ds = Chenxin.Lib.Hr.DAL.Pblish_Info.GetList(strPageSize, strPageIndex, strOrderField, strTableName, strWhere, FieldList, TableFieldList, true);
            //数据量
            count = (int)ds.Tables[1].Rows[0][0];

            string strHtml = string.Empty;

            int counts = (strPageIndex - 1) * strPageSize;

            if (!GetBulletinHtml(context, ds, counts, out strHtml))
            {
                context.Response.Write(retExecResult(Constants.ExecResult.Error, "生成HTML错误", ""));
            }
            stuPg.count = count;
            stuPg.data = strHtml.ToString();

            context.Response.Write(retExecResult(Constants.ExecResult.Succ, "OK", stuPg));
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    private bool GetBulletinHtml(HttpContext context, DataSet dslist, int counts, out string strHtml)
    {
        StringBuilder sb = new StringBuilder();
        string strType;
        string strTypeName="";
        sb.Append("<table width=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
        sb.Append("<thead>");
        sb.Append("<tr>");
        //sb.Append("<th width=\"5%\" style=\"text-align:center;\"><label id=\"lblck\"><input id=\"ckdel\" type=\"checkbox\" title=\"全选/反选\"/></label></th>");
        sb.Append("<th width=\"5%\">序号</th>");
        sb.Append("<th width=\"35%\">工作报告主题</th>");
        sb.Append("<th width=\"10%\">发布部门</th>");
        sb.Append("<th width=\"10%\">发布者</th>");
        sb.Append("<th width=\"10%\">发布时间</th>");
        sb.Append("<th width=\"15%\">信息类型</th>");
        sb.Append("<th width=\"5%\">详细</th>");
        sb.Append("<th width=\"5%\">附件</th>");
        sb.Append("</tr>");
        sb.Append("</thead>");
        sb.Append("<tbody>");

        DataTable dt = dslist.Tables[0];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\">", dt.Rows[i]["RecordId"].ToString());

            //sb.AppendFormat("<td style=\"text-align:center;\"><input name=\"ckpublic\" type=\"checkbox\" value=\"{0}\"/></td>", dt.Rows[i]["RecordId"].ToString());
            sb.AppendFormat("<td style=\"text-align:center;\">{0}</td>", (i + 1 + counts).ToString());
            sb.AppendFormat("<td>{0}</td>", dt.Rows[i]["Subject"].ToString());
            sb.AppendFormat("<td>{0}</td>", dt.Rows[i]["DepartName"].ToString());
            sb.AppendFormat("<td>{0}</td>", dt.Rows[i]["PublisherName"].ToString());
            sb.AppendFormat("<td>{0}</td>", Convert.ToDateTime(dt.Rows[i]["PublishTime"]).ToString("yyyy-MM-dd"));
            strType = dt.Rows[i]["InfoType"].ToString();
            for (int idxCnt = 0; idxCnt < Constants.PublicInfoType.Length; idxCnt++)
            {
                if (strType == Constants.PublicInfoType[idxCnt][2])
                {
                    strTypeName = Constants.PublicInfoType[idxCnt][0];
                }
            }
            sb.AppendFormat("<td>{0}</td>", strTypeName);
            sb.AppendFormat("<td style=\"text-align:center;\"><a name=\"{0}\" id=\"btndetail\" href=\"PublishDetailInfo.aspx?RecordId={0}\" title=\"详情\">详</a></td>", dt.Rows[i]["RecordId"].ToString());

            if (System.IO.File.Exists(context.Server.MapPath(Constants.DIRECTORY + dt.Rows[i]["Path"].ToString())))
                sb.AppendFormat("<td style=\"text-align:center;\"><a title=\"{0}\" id=\"btnattachment\" href=\"/service/Download.ashx?file=/{1}\" target=\"_blank\">附</a></td>", dt.Rows[i]["FileName"].ToString(), dt.Rows[i]["Path"].ToString());
            else
                sb.Append("<td style=\"text-align:center;\" title=\"无附件\"><span> - </span></td>");

            sb.Append("</tr>");
        }

        sb.Append("</tbody></table>");

        strHtml = sb.ToString();
        return true;
    }

}